package fairygui.editor.handlers
{
   import fairygui.editor.gui.EPackageItem;
   import fairygui.editor.gui.EUIPackage;
   import fairygui.editor.gui.EUIProject;
   import fairygui.editor.utils.UtilsFile;
   import flash.filesystem.File;
   import flash.system.System;
   
   public class SearchHandler
   {
       
      
      private var _index:int;
      
      private var _key:String;
      
      private var _results:Vector.<EPackageItem>;
      
      public function SearchHandler()
      {
         super();
         this._results = new Vector.<EPackageItem>();
      }
      
      public function search(param1:EUIProject, param2:String) : void
      {
         var pkg:EUIPackage = null;
         var xml:XML = null;
         var resources:XMLList = null;
         var rss:XMLList = null;
         var cxml:XML = null;
         var pi:EPackageItem = null;
         var project:EUIProject = param1;
         var key:String = param2;
         this._results.length = 0;
         key = key.toLowerCase();
         var pkgs:Vector.<EUIPackage> = project.getPackageList();
         for each(pkg in pkgs)
         {
            if(pkg.rootItem.treeNode)
            {
               if(pkg.name.toLowerCase().search(key) != -1)
               {
                  this._results.push(pkg.rootItem);
               }
               xml = UtilsFile.loadXML(new File(pkg.basePath + "/package.xml"));
               resources = xml.resources.elements();
               rss = resources.(@name.toString().toLowerCase().search(key) != -1);
               if(rss.length() > 0)
               {
                  pkg.ensureOpen();
                  for each(cxml in rss)
                  {
                     pi = pkg.getItem(cxml.@id);
                     if(pi)
                     {
                        this._results.push(pi);
                     }
                  }
               }
               System.disposeXML(xml);
            }
         }
      }
      
      public function get key() : String
      {
         return this._key;
      }
      
      public function get resultCount() : int
      {
         return this._results.length;
      }
      
      public function get nextResult() : EPackageItem
      {
         this._index++;
         if(this._index >= this._results.length)
         {
            this._index = 0;
         }
         return this._results[this._index];
      }
      
      public function get prevResult() : EPackageItem
      {
         var _loc1_:EPackageItem = this._results[this._index];
         this._index--;
         if(this._index < 0)
         {
            this._index = this._results.length - 1;
         }
         return _loc1_;
      }
   }
}
